const
    http = require('http'),
    httpProxy = require('http-proxy'),
    fs = require('fs'),
    dru = '/Volumes/jacky/web-sd/nodeStudy/day01/html';

// 新建一个代理 Proxy Server 对象  
var proxy = httpProxy.createProxyServer({});

// 捕获异常  
proxy.on('error', (err, req, res) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Something went wrong. And we are reporting a custom error message.');
});

// 在每次请求中，调用 proxy.web(req, res config) 方法进行请求分发  
var server = http.createServer((req, res) => {
    // 在这里可以自定义你的路由分发  
    var host = req.headers.host,
        ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress,
        Url = req.url,
        fileUrl = dru + Url;

    // console.log("client ip:" + ip + ", host:" + host);
    // console.log(host);
    console.log(Url);
    console.log(fileUrl);
    // httpProxy("/html/*.html",{});

    // switch (host) {
    //     case 'demo.jf-mall.com':
    //         proxy.web(req, res, { target: 'http://localhost:3000' });
    //         // console.log("3000");
    //         break;
    //     case 'vote.111.cn':
    //         proxy.web(req, res, { target: 'http://localhost:9527' });
    //         break;
    //     default:
    // }
    fs.readFile(fileUrl, (err, data) => {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('404');
            // res.end('Welcome to my server!');
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data.toString());
            res.end();
        }
    });

});

// console.log("listening on port 80");
server.listen(8000);